var websocket = null;          // 增加对websocket的支持
var timeoutProcess = null;     // 超时处理事件
var choice_success = false;
var arrChoice = [];    // 选择后的结果
var arrDialog = [];    // 画面对话框对象数组

function showModal(w, h, title, url, onLoad, onClose, type, msgText, onOkClick, onCancelClick) {
    if (onLoad === null) {
        onLoad = onLoadDialog;
    }
    if (onClose === null) {
        onClose = onCloseDialog;
    }
    $('body').dialog({
        mWidth: w,
        mHeight: h,
        mTitle: title,
        isIframe: 1,
        iframeSrc: url,
        dialog_type: type,
        msgText: msgText,
        onLoad: onLoad,
        onClose: onClose,
        onOkClick: onOkClick,
        onCancelClick: onCancelClick
    });

    //parent.$("#dialog_btn_ok").focus(); 设置聚焦按钮
}

//-----------------------------------------------------------------------------
// 相关回调函数
//-----------------------------------------------------------------------------
function onLoadDialog($dialog) {
    arrDialog.push($dialog);
}
function onCloseDialog($dialog) {
    var _exist = $.inArray($dialog, arrDialog);
    if (_exist >= 0) {
        arrDialog.splice($.inArray($dialog, arrDialog), 1);
    }
}


// 显示当前日期时间
function currentTime() {
    var d = new Date();
    var str = '';
    str += d.getFullYear() + '年';
    str += d.getMonth() + 1 + '月';
    str += d.getDate() + '日 ';
    //取得时间
    str += d.getHours() + ':';
    str += ((d.getMinutes() < 10) ? ('0' + d.getMinutes()) : d.getMinutes()) + ':';
    str += ((d.getSeconds() < 10) ? ('0' + d.getSeconds()) : d.getSeconds());

    return str;
}

//------------------------------------------------------------------------------
// 退出系统
//------------------------------------------------------------------------------
function doExitSystem() {
    showModal(343, 140, "退出系统", "", onLoadDialog, onCloseDialog, 1, "请问，确定要退出本系统吗？", onExitSystem);
}

function onExitSystem() {
    document.getElementById('form_logout').submit();
}

//------------------------------------------------------------------------------
// 显示和隐藏 Loading.. 信息框
//------------------------------------------------------------------------------
function showLoadmask() {
    $(document).swLoadmask({element: 'body'});
}
function hideLoadmask() {
    //setTimeout(function () {
    $.unmaskElement($(document));
    //}, 500);
}

// 设置菜单项状态
function setMenuItemStatus($obj) {
    var menuItem = $("li", $obj.parent());
    menuItem.removeClass("active");
    $obj.addClass("active");
}


// 显示与隐藏系统通知
function hideNoticeWnd(event) {
    $(".notice").hide(600);
}
function showNoticeWnd(event) {
    if ($(".notice").is(":hidden")) {
        $(".notice").show(600);
    }
}

/**
 * 给单个用户发送消息
 * @param {type} userName 用户名
 * @param {type} userId 用户标识
 * @param {type} message 消息
 * @returns {undefined} 成功标记
 */
function sendMessage(userName, userId, message) {
    $.ajax({
        type: "GET",
        url: this.basePath + "/message/send.html",
        timeout: 30 * 1000,
        data: "userName=" + userName + "&userId=" + userId + "&message=" + message,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        beforeSend: function () {
        }
    }).done(function (data) {
        if (data.Success === true) {
        }
    }
    ).fail(function (data) {
        ajaxError(data, 1);
    }).always(function ( ) {
    });
}

// 点击菜单项
function OnMenuItemClick(url) {
    window.location.assign(url);
}

// 菜单高度设置用
function clearHeight($object) {
    if ($object)
        $object.css("height", "");
}

function tuneHeight($object) {
    var $object1, $object2;
    if ($object.hasClass("level_1")) {
        $object1 = $object.parent("ul").parent();
        $object2 = $object.children("ul:eq(0)");
    }
    if ($object.hasClass("level_2")) {
        $object1 = $object.parent("ul");
        $object2 = $object.children("ul:eq(0)");
    }

    if (!$object2)
        return false;
    //clearHeight($("#huzo__menu"));
    clearHeight($object1);
    clearHeight($object2);
    var minHeight = Math.max($object1.height(), $object2.height());
    minHeight = Math.max($("#huzo__menu>ul").height() + 35, minHeight);

    $object2.css("height", minHeight);
    $object1.css("height", minHeight);
    $("#huzo__menu").css("height", minHeight);
}
////////////////////////////////////////////////////////////////////////////////
// 页面初始化

var transitionProp = function () {
    var n = document.createElement("fakeelement"),
            i = {transition: "transitionend", OTransition: "oTransitionEnd", MozTransition: "transitionend", WebkitTransition: "webkitTransitionEnd"};
    for (var t in i) {
        if (void 0 !== n.style[t])
            return i[t];
    }
}();

$(document).ready(function () {
    if ($(".error-msg").length > 0)
        $(".error-msg").remove();

    $(document).keydown(function (event) {
        if (event.keyCode === 13) {
            if ($(event.target).closest("textarea").length === 0)
                return false;
        }
    });

    // 用回车替代tab
    var $target = $('input, select, textarea, hidden');
    $target.bind('keyup', function (e) {
        var key = e.keyCode;
        if (key === 13) {
            var nxtIdx = $target.index(this) + 1;
            //if ($target.eq(nxtIdx).attr("type") === "textarea") {
            if ($(e.target).closest("textarea").length) {
                e.preventDefault();
                //$target.eq(nxtIdx).focus();
                return false;
            } else if ($target.eq(nxtIdx).attr("type") === "hidden") {
                nxtIdx = nxtIdx + 1;
                $target.eq(nxtIdx).focus();
            } else {
                $target.eq(nxtIdx).focus();
            }
        }
    });
    /*
     // 增加对websocket的支持
     if ('WebSocket' in window) {
     var wsUri = "ws://" + document.location.host + "/ons/ws/echo.html";
     websocket = new WebSocket(wsUri + "?userName=" + $("#UserName").val() + "&userId=" + $("#UserId").val());
     } else if ('MozWebSocket' in window) {
     var wsUri = "ws://" + document.location.host + "/ons/ws/echo.html";
     websocket = new MozWebSocket(wsUri + "?userName=" + $("#UserName").val() + "&userId=" + $("#UserId").val());
     } else {
     var wsUri = "ws://" + document.location.host + "/ons/sockjs/echo";
     websocket = new SockJS(wsUri);
     }
     if (websocket !== null) {
     websocket.onopen = function (event) {
     //console.log(event);
     };
     websocket.onmessage = function (event) {
     showNoticeWnd(event);
     };
     websocket.onerror = function (event) {
     //console.log(event);
     };
     websocket.onclose = function (event) {
     };
     }*/
    // 全屏菜单画面操作
    $('.main-menu').click(function (event) {
        $('aside').toggleClass('active');
        $('body').toggleClass('body-overlaid');
        $('#lines').toggleClass('close');       // 菜单横条标记
        event.stopPropagation();
    });
    // 这个为了显示快于隐藏，避免来回切换造成不好的视觉效果
    $('#huzo__menu li.menu__item').hover(
            function () {
                $(this).children("ul:eq(0)").fadeToggle(0, tuneHeight($(this)));
            },
            function () {
                $(this).children("ul:eq(0)").fadeToggle(0, tuneHeight($(this)));
            }
    );
    // 为模拟下拉选择框添加键盘事件
    $("#ele_1").keydown(function (e) {
        switch (e.keyCode) {
            case 39: //右键
                alert("右键");
                e.stopPropagation();
                e.preventDefault();
                break;
            case 40: //下键
                alert("下键");
                e.stopPropagation();
                e.preventDefault();
                break;
            default:
                break;
        }
    });

    var $search = $('.search');
    var clazz = 'search--active';
    // 搜索按钮
    $('#search_btn').on('click', function (event) {
        $search.addClass(clazz);
        $search.on(transitionProp, function (event) {
            $search.find('input').first().focus();
        });
    });

    // 搜索窗口关闭
    $('#search__form_butclose').on('click', function (event) {
        $search.removeClass(clazz);
    });

    // 搜索框回车直接进行搜索
    $("div.search").bind('keyup', function (e) {
        var key = e.keyCode;
        if (key === 13) {
            $("#but_filter").click();
        }
    });
    
    // 点击窗口任意位置或者搜索按钮，关闭打开的菜单以及检索框
    $(document).on('click', function (event) {
        if ($(event.target).is('.search--active')) {
            $search.removeClass(clazz);
        } else {
            if ($(event.target).is('.act__button')) {
                $search.removeClass(clazz);
            }
        }
        if ($(event.target).is('aside.active') || $(event.target).is('.body-overlaid')) {
            $('.main-menu').click();
        }
    });

    onPageResize();
    onPageReady();
});

$(window).bind("resize", function () {
    onPageResize();
});
$(window).bind("load", function () {
    onPageResize();
});

// 关闭浏览器之前要做的事情
function BeforeFrameHtmlUnload() {
}